package cn.devcat.sso.service.impl;

import cn.devcat.sso.entity.PageData;
import cn.devcat.sso.entity.Photo;
import cn.devcat.sso.entity.SearchCommonParam;
import cn.devcat.sso.mapper.PhotoMapper;
import cn.devcat.sso.service.IPhotoService;
import cn.devcat.sso.util.FileUtils;
import cn.devcat.sso.util.PageHelperUtil;
import cn.devcat.sso.util.TimeUtil;
import cn.devcat.sso.util.UserUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PhotoServiceImpl extends ServiceImpl<PhotoMapper, Photo> implements IPhotoService {

  @Resource
  PhotoMapper photoMapper;

  @Value("${devcat.photos}")
  private String photosDir;

  @Autowired
  UserUtil userUtil;

  @Override
  public PageData<Photo> getPhotoList(SearchCommonParam param) {
    PageHelperUtil.handle(param);
    List<Photo> photoList = photoMapper.getPhotoList(param);
    for (Photo photo : photoList) {
      String imagePath = photo.getImagePath();
      String filePath = imagePath.split("/data")[1];
      photo.setImagePath("https://www.huhailong.vip"+filePath);
    }
    return PageHelperUtil.makePageData(new PageInfo<>(photoList));
  }

  @Override
  public void uploadPhoto(MultipartFile file, String photoName, String photoDescribe) {
    if(file == null){
      throw new RuntimeException("上传的文件为空");
    }
    Photo photo = new Photo();
    photo.setPhotoDescribe(photoDescribe);
    photo.setPhotoName(photoName);
    photo.setCreateTime(LocalDateTime.now());
    photo.setUploadUserId(userUtil.getUserByRequest().getId());
    photo.setIsPublic(false);
    String originalFilename = file.getOriginalFilename();
    String suffix = FileUtils.suffix(originalFilename);
    String newFIleName = TimeUtil.getDateTime("yyyyMMddHHmmss") + suffix;
    File saveFile = new File(photosDir+newFIleName);
    try {
      file.transferTo(saveFile);
    } catch (IOException e) {
      throw new RuntimeException("保存图片错误:"+e.getMessage());
    }
    photo.setImagePath(photosDir+newFIleName);
    save(photo);
  }

  @Override
  public void delPhoto(List<Long> ids) {
    List<Photo> list = list(new QueryWrapper<Photo>().in("id", ids));
    List<String> collect = list.stream().map(Photo::getImagePath).collect(Collectors.toList());
    for (String s : collect) {
      FileUtils.delFile(s);
    }
    removeByIds(ids);
  }
}
